package com.cater.interceptor;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.cater.common.BaseEntity;
import com.cater.common.BaseQuery;
import com.cater.common.UserContext;
import com.cater.sys.entity.Role;
import com.cater.sys.entity.User;
import com.cater.utils.DictionaryUtil;

/**
 * 权限拦截器
 * 
 * @author zhengyangbo
 * 
 */
public class SecurityInterceptor implements HandlerInterceptor {

	/**
	 * 完成页面的render后调用
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object,
			Exception exception) throws Exception {

	}

	/**
	 * 在调用controller具体方法后拦截
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object,
			ModelAndView modelAndView) throws Exception {

	}

	/**
	 * 在调用controller具体方法前拦截
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		/*
		 * Subject subject= SecurityUtils.getSubject();
		 * System.out.println(subject.isAuthenticated());
		 */
		/*User user = (User) request.getSession().getAttribute("user_in_session");
		@SuppressWarnings("unchecked")
		List<Role> role = (List<Role>) request.getSession().getAttribute("role_in_session");
		if (role != null) {
			BaseQuery.isareaAdmin = null;
			for (Role role2 : role) {
				if (BaseQuery.isareaAdmin == null) {
					BaseQuery.isareaAdmin = role2.getRoleType();
				}
				if (BaseQuery.isareaAdmin > role2.getRoleType()) {
					BaseQuery.isareaAdmin = role2.getRoleType();
				}
			}
		}
		Integer depid = (Integer) request.getSession().getAttribute("deppid_in_session");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (user != null) {
			BaseEntity.userid = user.getId();
			BaseQuery.userIds = user.getId();
			BaseQuery.allUserIds = UserContext.getUserIds();
			BaseEntity.date = sdf.format(new Date());
			if (BaseQuery.isareaAdmin == 1) {
				UserContext.setIsadmin(true);
				BaseQuery.setIsadmin(true);
			} else if (BaseQuery.isareaAdmin == 2) {
				UserContext.setIsCompanyadmin(true);
				BaseQuery.setIscompanyadmin(true);
			} else if (BaseQuery.isareaAdmin == 3) {
				UserContext.setIsDepadmin(true);
				BaseQuery.setIsdepadmin(true);
			} else {
				BaseQuery.setIsadmin(false);
				UserContext.setIsadmin(false);
			}
			BaseQuery.setCompanyId(depid);

		}*/

		// 装配字典Util对象
		request.getSession().setAttribute("DictionaryUtil", DictionaryUtil.DictionaryUtil);
		return true;
	}
}
